var express = require('express')
var ObjectID = require('mongodb').ObjectID
var fs = require('fs')
let g = require('./global')
var Lesson = require('./models/lesson')
var LessonDetail = require('./models/lessondetail')
var Book = require('./models/book')
var BookDetail = require('./models/bookdetail')
var Yo = require('./models/yo')
var YoDetail = require('./models/yodetail')
module.exports.admin = function (req, res) {
    savePath('LESSON', 'LESSONDETAIL').then((data) => {
        Lesson.find((error, data) => {
            if (error) {
                return res.status(500).send(error.message)
            }
            res.render('index.html', {
                data: data
            })
        })
    }).catch((error) => {
        return res.status(500).send(error.message)
    })
}

module.exports.add = function (req, res) {
    res.render('add.html')
}

module.exports.postAdd = function (req, res) {
    let newData = req.body
    getPath().then((obj) => {
        let colleciton = choseCollection(obj.globalPath)
        let detailcollection = choseDetailCollection(obj.globalPath)
        newData.denominator = parseInt(newData.denominator)
        newData.numerator = parseInt(newData.numerator)
        console.log(newData);
        new colleciton(newData).save((error, result) => {
            if (error) {
                return res.status(500).send(error)
            }
            new detailcollection({
                name: newData.name,
                cluster: newData.cluster,
                denominator: newData.denominator,
                numerator: newData.numerator,
                today: 0,
                desc: []
            }).save((error, result) => {
                if (error) {
                    return res.status(500).send(error.message)
                }
                res.statusCode = 302
                let urlPath = choseUrlPath(obj.globalPath)
                res.setHeader('Location', urlPath)
                res.end()
            })
        })
    }).catch((error) => {
        return res.status(500).send(error.message)
    })
}

module.exports.delete = function (req, res) {
    getPath().then((obj) => {
        let colleciton = choseCollection(obj.globalPath)
        let detailcollection = choseDetailCollection(obj.globalPath)
        ///use id find which one
        let id = req.query.id
        colleciton.findOne({"_id":new ObjectID(id)}, (error, result) => {
            if (error) {
                return res.status(500).send(error.message)
            }
            ///use result.name delete detail
            detailcollection.deleteOne({ name: result.name }, (error, result) => {
                if (error) {
                    return res.status(500).send(error.message)
                }
                /// delete outside
                colleciton.deleteOne({"_id": new ObjectID(id)}, (error, result) => {
                    if (error) {
                        return res.status(500).send(error.message)
                    }
                    let urlPath = choseUrlPath(obj.globalPath)
                    res.statusCode = 302
                    res.setHeader('Location', urlPath)
                    res.end()
                })
            })
        })
    })
}

module.exports.findById = function (req, res) {    
    getPath().then((obj) => {
        let colleciton = choseCollection(obj.globalPath)
        colleciton.findOne({"_id": new ObjectID(req.query.id)}, (error, result)=> {
            if (error) {
                return res.status(500).send(error.message)
            }
            console.log(result);
            res.render('edit.html', {
                data: result
            })
        })
    }).catch((error) => {
        return res.status(500).send(error.message)
    })
}

module.exports.edit = function (req, res) {
    let ele = req.body
    ele.numerator = parseInt(ele.numerator)
    ele.denominator = parseInt(ele.denominator)
    getPath().then((obj) => {
        let colleciton = choseCollection(obj.globalPath)
        let detailcollection = choseDetailCollection(obj.globalPath)
        /// outside find and update
        colleciton.findByIdAndUpdate({"_id": new ObjectID(ele.id)}, ele, (error, result)=> {
            if (error) {
                return res.status(500).send(error.message)
            } else {
                /// detail find  and update
                updateDetail(detailcollection, ele).then((data)=> {
                    res.statusCode = 302
                    let urlPath = choseUrlPath(obj.globalPath)
                    res.setHeader('Location', urlPath)
                    res.end()
                }).catch((error)=> {
                    return res.status(500).send(error.message)
                })
            }
        })
    }).catch((error) => {
        return res.status(500).send(error.message)
    })
}

module.exports.book = function (req, res) {
    savePath('BOOK', 'BOOKDETAIL').then((obj) => {
        Book.find((error, data) => {
            if (error) {
                return res.status(500).send(error.message)
            }
            res.render('index.html', {
                data: data
            })
        })
    }).catch((error) => {
        return res.status(500).send(error.message)
    })
}

module.exports.yo = function (req, res) {
    savePath('YO', 'YODETAIL').then((obj) => {
        Yo.find((error, data) => {
            if (error) {
                return res.status(500).send(error.message)
            }
            res.render('index.html', {
                data: data
            })
        })
    }).catch((error) => {
        return res.status(500).send('发生错误')
    })
}

module.exports.detail = function (req, res) {
    getPath().then((obj) => {
        let detailcollection = choseDetailCollection(obj.globalPath)
        detailcollection.findOne(req.query, (error, result)=> {
            if (error) {
                return res.status(500).send(error.message)
            }
            console.log(result);
            let data = {}
            data.name = result.name
            data.cluster = result.cluster
            data.denominator = result.denominator
            data.numerator = result.numerator
            data.today = result.today
            data.desc = []
            for (let i = 0; i < result.desc.length; i++) {
                let item = {}
                item.time = result.desc[i].time
                item.today = result.desc[i].today
                item.text = result.desc[i].text
                data.desc.push(item)
            }
            res.status(200).render('detail.html', {
                data: data
            })
        })
    }).catch((error) => {
        return res.status(500).send(error.message)
    })
}
/// 同步创建详情
function createDetail(collection, data) {
    return new Promise((resolve, reject) => {
        new collection(data).save((error, result) => {
            if (error) {
                return reject(error)
            }
            resolve(result)
        })
    })
}

/// 同步更新详情
function updateDetail(colleciton, updateData) {
    return new Promise((resolve, reject) => {
        colleciton.findOne({"name": updateData.name}, (error, result)=> {
            if (error) {
                return reject(error)
            }
            colleciton.findByIdAndUpdate({"_id": result.id}, {
                cluster: updateData.cluster,
                denominator: updateData.denominator,
                numerator: updateData.numerator,
            }, (error, result)=> {
                if (error) {
                    return reject(error)
                }
                resolve(result)
            })
        })
    })
}

/// 同步删除详情
function deleteDetail(id, path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, (error, data) => {
            if (error) {
                return reject(error)
            }

            let jsonData = JSON.parse(data)
            let detail = jsonData.data
            let index = detail.findIndex((item) => {
                return item.id === parseInt(id)
            })
            detail.splice(index, 1)
            fs.writeFile(path, JSON.stringify(jsonData), (error) => {
                if (error) {
                    return reject(error)
                }
                resolve(null)
            })
        })
    })
}

function savePath(g, d) {
    return new Promise((resolve, reject) => {
        fs.readFile('global.json', (error, data) => {
            if (error) {
                return reject(error)
            }
            let jsonData = JSON.parse(data)
            jsonData.globalPath = g
            jsonData.detailPath = d
            let json = JSON.stringify(jsonData)
            fs.writeFile('global.json', json, (error) => {
                if (error) {
                    return reject(error)
                }
                resolve(jsonData)
            })
        })
    })
}

function getPath() {
    return new Promise((resolve, reject) => {
        fs.readFile('global.json', (error, data) => {
            if (error) {
                return reject(error)
            }
            let jsonData = JSON.parse(data)
            resolve(jsonData)
        })
    })
}

function choseCollection(path) {
    let colleciton = null
    if (path === 'BOOK') {
        colleciton = Book
    } else if (path === 'LESSON') {
        colleciton = Lesson
    } else if (path === 'YO') {
        colleciton = Yo
    }
    return colleciton
}

function choseDetailCollection(path) {
    let detailcollection = null
    if (path === 'BOOK') {
        detailcollection = BookDetail
    } else if (path === 'LESSON') {
        detailcollection = LessonDetail
    } else if (path === 'YO') {
        detailcollection = YoDetail
    }
    return detailcollection
}

function choseUrlPath(path) {
    let urlPath = '/admin'
    if (path === 'BOOK') {
        urlPath = '/admin/book'
    } else if (path === 'YO') {
        urlPath = '/admin/yo'
    }
    return urlPath
}